/**
 * OnlineInfoInterceptor.java 1.0 2007-5-24 下午10:59:49,创建 by yangfan
 */


package org.in4j.bbs.interceptor;

import java.sql.Timestamp;
import java.util.Map;

import javax.servlet.ServletContext;
import javax.servlet.http.HttpServletRequest;

import org.in4j.bbs.common.Consts;
import org.in4j.bbs.model.OnlineInfo;
import org.in4j.bbs.model.User;
import org.in4j.bbs.service.UserService;
import org.springframework.web.context.WebApplicationContext;
import org.springframework.web.context.support.WebApplicationContextUtils;

import com.opensymphony.webwork.ServletActionContext;
import com.opensymphony.xwork.ActionInvocation;
import com.opensymphony.xwork.interceptor.AroundInterceptor;

/**
 * 在线信息拦截器<br>
 * 把当前用户的OnlineInfo(在线信息)set到OnlineInfoAware里
 * @author yangfan
 * @version 1.0 2007-5-24 下午10:59:49,创建
 */
public class OnlineInfoInterceptor extends AroundInterceptor
{
	private static final long serialVersionUID = -8602095953661178608L;

	@Override
	protected void after(ActionInvocation dispatcher, String result) throws Exception
	{
	}

	@Override
	protected void before(ActionInvocation invocation) throws Exception
	{
		Map session = invocation.getInvocationContext().getSession();
		HttpServletRequest request = ServletActionContext.getRequest();
		ServletContext servletContext = ServletActionContext.getServletContext();
		WebApplicationContext ctx = WebApplicationContextUtils.getRequiredWebApplicationContext(servletContext);
		final UserService userService = (UserService)ctx.getBean("userService",UserService.class);
		OnlineInfo onlineInfo = (OnlineInfo)session.get(Consts.SESSION_USER_INFO);
		if(onlineInfo == null)
		{
			onlineInfo = new OnlineInfo();
			onlineInfo.setIp(request.getRemoteAddr());
			onlineInfo.setLoginTime(new Timestamp(System.currentTimeMillis()));
			User user = userService.getUserByName(User.GUEST);
			onlineInfo.setUser(user);
		}
		Object action = invocation.getAction();
		if(action instanceof OnlineInfoAware)
		{
			OnlineInfoAware myAction = (OnlineInfoAware)action;
			myAction.setOnlineInfo(onlineInfo);
		}
	}
}
